<template>
    <PageView>
        <!-- 筛选数据的表单 -->
        <vxe-form ref="formRef"
                  :data="searchFormData"
                  title-colon
                  :rules="formRules"
                  :valid-config="{theme: 'normal'}">
            <!-- 开始日期 -->
            <vxe-form-item title="开始日期" field="startDate" :item-render="{}">
                <template #default="params">
                    <vxe-input v-model="searchFormData.startDate"
                               placeholder="选择日期"
                               type="date"
                               @change="searchFormChangeEvent(params)"/>
                </template>
            </vxe-form-item>

            <!-- 结束日期 -->
            <vxe-form-item title="结束日期" field="endDate" :item-render="{}">
                <template #default="params">
                    <vxe-input v-model="searchFormData.endDate"
                               placeholder="选择日期"
                               type="date"
                               @change="searchFormChangeEvent(params)"/>
                </template>
            </vxe-form-item>

            <!-- 查询按钮 -->
            <vxe-form-item :item-render="{}">
                <template #default="params">
                    <vxe-button type="submit" status="primary" content="查询"
                                @click="searchFormChangeEvent(params)"></vxe-button>
                </template>
            </vxe-form-item>
        </vxe-form>

        <!-- 表格的工具栏 -->
        <vxe-toolbar ref="toolbarRef" custom/>

        <!-- 表格 -->
        <vxe-table
            id="xxxJobListTable"
            ref="tableRef"
            border
            stripe
            empty-text="暂无数据"
            min-height="300"
            :loading="tableLoading"
            :column-config="{resizable: true}"
            :row-config="{isHover: true}"
            :checkbox-config="{labelField: 'id', highlight: false, range: true}"
            :data="xxlJobListStore.dataList">
            <vxe-column field="jobId" title="任务 ID" width="120px" sortable/>
            <vxe-column field="jobManager" title="任务管理器" min-width="100px" show-overflow/>
            <vxe-column field="jobHandler" title="任务处理器" min-width="200px" show-overflow/>
            <vxe-column field="jobName" title="任务名称" min-width="200px" show-overflow/>
            <vxe-column field="jobDate" title="任务时间" min-width="100px" show-overflow/>
            <vxe-column title="操作" fixed="right" width="150px">
                <template #default="{row}">
                    <vxe-button mode="text" status="error" @click="modifyEvent(row)">编辑</vxe-button>
                    <vxe-button mode="text" status="primary" @click="submitEvent(row)">详细</vxe-button>
                    <!--                    <vxe-button mode="text" content="更多">-->
                    <!--                        <template #dropdowns>-->
                    <!--                            <vxe-button mode="text">删除数据</vxe-button>-->
                    <!--                            <vxe-button mode="text">导出数据</vxe-button>-->
                    <!--                            <vxe-button mode="text">导入数据</vxe-button>-->
                    <!--                        </template>-->
                    <!--                    </vxe-button>-->
                </template>
            </vxe-column>
        </vxe-table>

        <!-- 分页导航栏 -->
        <vxe-pager
            style="margin-top: 10px"
            align="right"
            v-model:currentPage="xxlJobListStore.currentPage"
            v-model:pageSize="xxlJobListStore.currentPageSize"
            :total="xxlJobListStore.totalRow"
            @page-change="pagerChangeEvent">
        </vxe-pager>
    </PageView>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { useXxlJobListStore } from '@/store/UseXxlJobListStore.ts';
import { XxlJobVO } from '@/entiy/vo/XxlJobVO.ts';
import { VxeToolbarInstance } from 'vxe-pc-ui/types/components/toolbar';
import { VxeTableInstance } from 'vxe-pc-ui/types/components/table';
import { XxlJobListFormData } from '@/entiy/form/XxlJobListFormData.ts';
import XEUtils from 'xe-utils';
import { VxeFormInstance, VxeFormPropTypes } from 'vxe-pc-ui';
import PageView from '@/views/layout/PageView.vue';

const xxlJobListStore = useXxlJobListStore();

const searchFormData = ref<XxlJobListFormData>({
    // 默认查询半年
    startDate: XEUtils.toDateString(XEUtils.getWhatYear(new Date(), -1), 'yyyy-MM-dd'),
    endDate: XEUtils.toDateString(new Date(), 'yyyy-MM-dd')
});

const tableLoading = ref(false);

// 工具栏
const toolbarRef = ref<VxeToolbarInstance>();
const tableRef = ref<VxeTableInstance>();

onMounted(() => {
    // 工具和表格建立关联关系
    const $table = tableRef.value;
    const $toolbar = toolbarRef.value;
    if ($table && $toolbar) {
        $table.connect($toolbar);
    }

    // 加载数据
    tableLoading.value = true;
    xxlJobListStore.getJobList(searchFormData.value).catch((reason) => {
        console.error('获取列表失败:', reason);
    }).finally(() => {
        tableLoading.value = false;
    });
});

// 分页导航栏更新事件
const pagerChangeEvent = () => {
    tableLoading.value = true;
    xxlJobListStore.getJobList(searchFormData.value).catch((reason) => {
        console.error('获取列表失败:', reason);
    }).finally(() => {
        tableLoading.value = false;
    });
};

// 表单实例
const formRef = ref<VxeFormInstance<XxlJobListFormData>>();

// 自定义校验规则
const formRules = ref<VxeFormPropTypes.Rules<XxlJobListFormData>>({
    startDate: [
        {
            required: true,
            content: '开始日期不能为空'
        },
        {
            validator ({ itemValue }) {
                if (XEUtils.isNull(itemValue) || !XEUtils.isValidDate(new Date(itemValue))) {
                    return new Error('请选择一个合法的日期');
                }
            }
        }
    ],

    endDate: [
        {
            required: true,
            content: '开始日期不能为空'
        },
        {
            validator ({ itemValue }) {
                if (XEUtils.isNull(itemValue) || !XEUtils.isValidDate(new Date(itemValue))) {
                    return new Error('请选择一个合法的日期');
                }
            }
        }
    ]
});

// 表单更新事件
const searchFormChangeEvent = (_params: any) => {
    console.log('SearchFormChangeEvent:', searchFormData.value);
    const $form = formRef.value;
    if (!$form) {
        return;
    }

    // 校验整个表单
    $form.validate().then((errMap) => {
        // ErrMap 没有 Undefined 表示没有校验失败的表单
        if (XEUtils.isUndefined(errMap)) {
            // 校验成功就查询数据
            tableLoading.value = true;
            xxlJobListStore.getJobList(searchFormData.value).then((data) => {
                console.log('获取列表成功:', data);
            }).catch((reason) => {
                console.error('获取列表失败:', reason);
            }).finally(() => {
                tableLoading.value = false;
            });
        }
    });
};

const modifyEvent = (row: XxlJobVO) => {
    console.log('ModifyEvent:', row);
};

const submitEvent = (row: XxlJobVO) => {
    console.log('SubmitEvent:', row);
};
</script>
